package cn.bugstack.mybatis.binding;

import cn.bugstack.mybatis.binding.session.SqlSession;

import java.lang.reflect.Proxy;

public class MapperProxyFactory <T>{
    private final Class<T> mapperInterface;

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @SuppressWarnings("unchecked")
    public T newInstance(SqlSession sqlSession) {
        final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface);
        /**
         * mapperInterface.getClassLoader(): 获取 Mapper 接口的类加载器。
         * new Class[]{mapperInterface}: 指定代理实例实现的接口，这里是 mapperInterface。
         * mapperProxy: 作为 InvocationHandler 的实现，处理对接口方法的调用
         * */
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }
}
